package com.example.piece

import android.app.ActivityManager
import android.content.Context
import android.os.Process
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.example.base.BaseApp
import com.example.base.tools.ConfigTool
import com.example.base.tools.LauncherIcon.LauncherIconManager
import com.example.base.tools.upgrade.UpgradeTool
import com.example.piece.constant.Key
import com.example.piece.entity.UserInfoEntity
import com.kongzue.dialogx.DialogX
import com.sunchen.netbus.NetStatusBus
import com.sunchen.netbus.annotation.NetSubscribe
import com.sunchen.netbus.type.Mode
import com.sunchen.netbus.type.NetType
import com.therouter.TheRouter
import com.wenming.library.LogReport
import com.wenming.library.save.imp.CrashWriter
import com.wenming.library.upload.email.EmailReporter
import xyz.doikki.videoplayer.BuildConfig
import xyz.doikki.videoplayer.ijk.IjkPlayerFactory
import xyz.doikki.videoplayer.player.VideoViewConfig
import xyz.doikki.videoplayer.player.VideoViewManager
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException


@Suppress("unused", "ConstantConditionIf")
class App : BaseApp() {

    companion object {
        var isHightWX = false////是否是高版本微信

        const val isDebug = true
        var userLoginCodeEntity: UserInfoEntity = UserInfoEntity()
        var USER_TOKEN =
            "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxNDg1NCIsImV4cCI6MTY5MjE1MzgxOX0.QObOvSc1SMNIaAFq9dz_h7W0eej7R38dM4GUqhXx57s"

    }

    override fun attachBaseContext(base: Context?) {
        TheRouter.isDebug = isDebug

        super.attachBaseContext(base)
    }

    override fun onCreate() {
        super.onCreate()
        initPush()
        //播放器配置，注意：此为全局配置，按需开启
        //播放器配置，注意：此为全局配置，按需开启
        VideoViewManager.setConfig(VideoViewConfig.newBuilder()
            .setLogEnabled(BuildConfig.DEBUG) //调试的时候请打开日志，方便排错
            /** 软解，支持格式较多，可通过自编译so扩展格式，结合 [xyz.doikki.dkplayer.widget.videoview.IjkVideoView] 使用更佳  */
            .setPlayerFactory(IjkPlayerFactory.create()) //                .setPlayerFactory(AndroidMediaPlayerFactory.create()) //不推荐使用，兼容性较差
            /** 硬解，支持格式看手机，请使用CpuInfoActivity检查手机支持的格式，结合 [xyz.doikki.dkplayer.widget.videoview.ExoVideoView] 使用更佳  */ //                .setPlayerFactory(ExoMediaPlayerFactory.create())
            // 设置自己的渲染view，内部默认TextureView实现
            //                .setRenderViewFactory(SurfaceRenderViewFactory.create())
            // 根据手机重力感应自动切换横竖屏，默认false
            //                .setEnableOrientation(true)
            // 监听系统中其他播放器是否获取音频焦点，实现不与其他播放器同时播放的效果，默认true
            //                .setEnableAudioFocus(false)
            // 视频画面缩放模式，默认按视频宽高比居中显示在VideoView中
            //                .setScreenScaleType(VideoView.SCREEN_SCALE_MATCH_PARENT)
            // 适配刘海屏，默认true
            //                .setAdaptCutout(false)
            // 移动网络下提示用户会产生流量费用，默认不提示，
            // 如果要提示则设置成false并在控制器中监听STATE_START_ABORT状态，实现相关界面，具体可以参考PrepareView的实现
            //                .setPlayOnMobileNetwork(false)
            // 进度管理器，继承ProgressManager，实现自己的管理逻辑
            //                .setProgressManager(new ProgressManagerImpl())
            .build())


        USER_TOKEN = ConfigTool.getString(Key.DataKey.TOKEN,
            "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxNDg1NCIsImV4cCI6MTY5MjE1MzgxOX0.QObOvSc1SMNIaAFq9dz_h7W0eej7R38dM4GUqhXx57s")
        //  initCrashReport()
        // 获取当前包名
        val packageName: String = context.getPackageName()
// 获取当前进程名
        // 获取当前进程名
        getProcessName(this)?.let { Log.e("getProcessName", it) }
        if (packageName.equals(getProcessName(this))) {//初始化一次 处理多进程事件
            // ARoute 初始化
            if (isDebug) {
                //   ARouter.openLog()
                //  ARouter.openDebug()
            }
            //   ARouter.init(context)

            // 网络监听框架初始化
            NetStatusBus.getInstance().init(context)
            NetStatusBus.getInstance().register(context)


            UpgradeTool.init(providerAuthority = "${applicationInfo.packageName}.fileProvider")

// 获取当前包名
            // 获取当前包名
            val packageName: String = context.getPackageName()
// 获取当前进程名
            // 获取当前进程名
            val processName =
                getProcessName(Process.myPid())
            // 设置是否为上报进程

            LauncherIconManager.register(this)

            DialogX.init(this)


        }
    }

    @NetSubscribe(mode = Mode.AUTO)
    fun onNetChanged(netType: NetType) {
        // WIFI 断开    ->  NONE
        // WIFI 连接    ->  WIFI
        // 连接Wi-Fi的时候操作移动数据则无效，不会产生任何事件
        // 打开移动数据  ->  MOBILE
        // 关闭移动数据  ->  NONE

        // 打开移动数据的时候关闭Wi-Fi
        // 先 NONE      ->  MOBILE

        // 打开移动数据的时候连接Wi-Fi
        // 连续产生两次 WIFI 事件
        Toast.makeText(this, "网络发生变化, ${netType.name}~", Toast.LENGTH_SHORT).show()
        Log.e("netChanged", "网络发生变化, ${netType.name}~")
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    fun getProcessName(pid: Int): String? {
        var reader: BufferedReader? = null
        try {
            reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
            var processName: String = reader.readLine()
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim { it <= ' ' }
            }
            return processName
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
        } finally {
            try {
                if (reader != null) {
                    reader.close()
                }
            } catch (exception: IOException) {
                exception.printStackTrace()
            }
        }
        return null
    }

    private fun initCrashReport() {
        LogReport.getInstance()
            .setCacheSize((30 * 1024 * 1024).toLong()) //支持设置缓存大小，超出后清空
            .setWifiOnly(true) //设置只在Wifi状态下上传，设置为false为Wifi和移动网络都上传
            .setLogDir(
                getApplicationContext(),
                getFilesDir().getAbsolutePath() + "/"
            )//定义路径为：sdcard/[app name]/


            .setLogSaver(CrashWriter(applicationContext)) //支持自定义保存崩溃信息的样式
/*
            .setEncryption( AESEncode()) //支持日志到AES加密或者DES加密，默认不开启
*/
            .init(applicationContext)
        initEmailReporter()
    }

    /**
     * 使用EMAIL发送日志
     */
    private fun initEmailReporter() {
        val email = EmailReporter(this)
        email.setReceiver("sam1135520344@163.com") //收件人
        email.setSender("sam1135520344@163.com") //发送人邮箱
        email.setSendPassword("DBXNOJZQPEVNOVZV") //邮箱的客户端授权码，注意不是邮箱密码
        email.setSMTPHost("smtp.163.com") //SMTP地址
        email.setPort("465") //SMTP 端口
        LogReport.getInstance().setUploadType(email)
    }
}

fun initPush() {
    val wxVersionCode: String = getWXVersionCode(BaseApp.context)
    val split = wxVersionCode.split(".").toTypedArray()
    if (split[0].toInt() > 6) {
        App.isHightWX = true
    } else if (split[0].toInt() == 6 && split[1].toInt() > 7) {
        App.isHightWX = true
    } else if (split[0].toInt() == 6 && split[1].toInt() == 7 && split[2].toInt() > 2) {
        App.isHightWX = true
    }
}

fun getWXVersionCode(context: Context): String {
    val pckMan = context.packageManager
    val items = ArrayList<HashMap<String, Any>>()
    val packageInfo = pckMan.getInstalledPackages(0)
    for (pInfo in packageInfo) {
        /* HashMap<String, Object> item = new HashMap<String, Object>();
            item.put("appimage", pInfo.applicationInfo.loadIcon(pckMan));
            item.put("packageName", pInfo.packageName);
            item.put("versionCode", pInfo.versionCode);
            item.put("versionName", pInfo.versionName);
            item.put("appName", pInfo.applicationInfo.loadLabel(pckMan).toString());
            items.add(item);*/
        if ("com.tencent.mm" == pInfo.packageName) {
            return pInfo.versionName
        }
    }
    return "6.7.2"
}

private fun getProcessName(context: Context): String? {
    val am: ActivityManager =
        context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val runningApps: List<ActivityManager.RunningAppProcessInfo> =
        am.getRunningAppProcesses()
            ?: return null
    for (proInfo in runningApps) {
        if (proInfo.pid === android.os.Process.myPid()) {
            if (proInfo.processName != null) {
                return proInfo.processName
            }
        }
    }
    return null
}